package com.sunday.pinxinghui.model.products;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.sunday.common.adapter.CommenAdapter;
import com.sunday.common.base.BaseActivity;
import com.sunday.common.model.ResultDO;
import com.sunday.common.utils.Constants;
import com.sunday.common.widgets.EmptyLayout;
import com.sunday.common.widgets.NoScrollGridView;
import com.sunday.common.widgets.ptr.PtrClassicFrameLayout;
import com.sunday.common.widgets.ptr.PtrDefaultHandler;
import com.sunday.common.widgets.ptr.PtrFrameLayout;
import com.sunday.common.widgets.ptr.PtrHandler;
import com.sunday.common.widgets.recyclerView.HorizontalDividerItemDecoration;
import com.sunday.pinxinghui.R;
import com.sunday.pinxinghui.adapter.CommonAdapter;
import com.sunday.pinxinghui.adapter.IndexMiaoShaAdapter;
import com.sunday.pinxinghui.adapter.ViewHolder;
import com.sunday.pinxinghui.entity.Comment;
import com.sunday.pinxinghui.entity.IndexProduct;
import com.sunday.pinxinghui.model.ShowBigImage;
import com.sunday.pinxinghui.network.ApiClient;
import com.sunday.pinxinghui.widgets.MyRatingBar;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by 刘涛 on 2017/8/27.
 */

public class CommentListActivity extends BaseActivity {

    @Bind(R.id.title_view)
    TextView titleView;
    @Bind(R.id.recycler_view)
    RecyclerView recyclerView;
    @Bind(R.id.ptr_frame)
    PtrClassicFrameLayout ptrFrame;
    @Bind(R.id.empty_layout)
    EmptyLayout emptyLayout;

    private LinearLayoutManager layoutManager;
    private CommonAdapter<Comment> adapter;
    private List<Comment> dataSet = new ArrayList<>();
    private int pageNo = 1, lastVisibleItem;
    private boolean isCanloadMore;
    private long productId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_recycler_list);
        ButterKnife.bind(this);
        titleView.setText("评论列表");
        productId = getIntent().getLongExtra("productId", 0);
        initRecyclerView();
        getData();
    }

    private void initRecyclerView() {
        emptyLayout.setErrorType(EmptyLayout.HIDE_LAYOUT);
        layoutManager = new LinearLayoutManager(mContext);
        recyclerView.setLayoutManager(layoutManager);
        adapter = new CommonAdapter<Comment>(mContext, R.layout.list_comment_item, dataSet) {
            @Override
            public void convert(ViewHolder holder, Comment comment, int position) {
                bind(holder, comment, position);
            }
        };
        recyclerView.setAdapter(adapter);
        recyclerView.addItemDecoration(new HorizontalDividerItemDecoration.Builder(mContext)
                .drawable(R.drawable.shape_divider)
                .build());
        ptrFrame.setPtrHandler(new PtrHandler() {
            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                pageNo = 1;
                getData();
            }

            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                return PtrDefaultHandler.checkContentCanBePulledDown(frame, recyclerView, header);
            }
        });
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE
                        && lastVisibleItem + 1 == adapter.getItemCount() && isCanloadMore) {
                    getData();
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                lastVisibleItem = layoutManager.findLastVisibleItemPosition();
            }
        });
        emptyLayout.setOnLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pageNo = 1;
                getData();
            }
        });
    }

    private void bind(ViewHolder holder, final Comment comment, int position) {
        ImageView commentUserLogo = holder.getView(R.id.comment_user_logo);
        TextView commentUserName = holder.getView(R.id.comment_user_name);
        TextView commentUserTime = holder.getView(R.id.comment_user_time);
        TextView commentUserContent = holder.getView(R.id.comment_user_content);
        NoScrollGridView commentUserImgs = holder.getView(R.id.comment_user_imgs);
        Glide.with(mContext)
                .load(comment.getMemberLogo())
                .error(R.mipmap.ic_default)
                .into(commentUserLogo);
        commentUserName.setText(comment.getMemberName());
        commentUserTime.setText(comment.getTime());
        commentUserContent.setText(comment.getContent());
        if (comment.getImages() != null && comment.getImages().size() > 0) {
            commentUserImgs.setAdapter(new CommenAdapter<String>(mContext, comment.getImages(), R.layout.list_comment_img_item) {
                @Override
                public void convert(com.sunday.common.adapter.ViewHolder helper, String item, int position) {
                    ImageView imgView = helper.getView(R.id.comment_img);
                    Glide.with(mContext)
                            .load(item)
                            .error(R.mipmap.ic_default)
                            .into(imgView);
                }
            });
            commentUserImgs.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    Intent intent = new Intent(mContext, ShowBigImage.class);
                    intent.putStringArrayListExtra("data", (ArrayList<String>) comment.getImages());
                    intent.putExtra("index", position);
                    mContext.startActivity(intent);
                }
            });
        }
        MyRatingBar serviceRatingBar=holder.getView(R.id.rating_bar);
        serviceRatingBar.setRating((int) comment.getScore(),R.drawable.rating_bar,false,15);

    }

    private void getData() {
        showLoadingDialog(0);
        Call<ResultDO<List<Comment>>> call = ApiClient.getApiAdapter().getComments(productId, pageNo, Constants.PAGE_SIZE);
        call.enqueue(new Callback<ResultDO<List<Comment>>>() {
            @Override
            public void onResponse(Call<ResultDO<List<Comment>>> call, Response<ResultDO<List<Comment>>> response) {
                if (isFinish) {
                    return;
                }
                dissMissDialog();
                ptrFrame.refreshComplete();
                ResultDO<List<Comment>> resultDO = response.body();
                if (resultDO == null) {
                    return;
                }

                if (resultDO.getCode() == 0) {
                    if (resultDO.getResult() == null) {
                        return;
                    }
                    if (pageNo == 1) {
                        dataSet.clear();
                    }
                    if (resultDO.getResult().size() == Constants.PAGE_SIZE) {
                        isCanloadMore = true;
                        pageNo++;
                    } else {
                        isCanloadMore = false;
                    }
                    dataSet.addAll(resultDO.getResult());
                    if (dataSet.size() > 0) {
                        emptyLayout.setErrorType(EmptyLayout.HIDE_LAYOUT);
                    } else {
                        emptyLayout.setErrorType(EmptyLayout.NODATA);
                    }
                    adapter.notifyDataSetChanged();
                }
            }

            @Override
            public void onFailure(Call<ResultDO<List<Comment>>> call, Throwable t) {
                dissMissDialog();
                ptrFrame.refreshComplete();
            }
        });
    }
}
